package com.ikingtech.platform.service.system.division.controller;

import com.ikingtech.framework.sdk.base.model.BatchParam;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.division.api.DivisionApi;
import com.ikingtech.framework.sdk.division.model.DivisionDTO;
import com.ikingtech.framework.sdk.enums.system.division.DivisionLevelEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import com.ikingtech.platform.service.system.division.entity.DivisionDO;
import com.ikingtech.platform.service.system.division.service.DivisionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * 系统管理-行政区划模块
 *
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
@ApiController(value = "/system/division", name = "系统管理-行政区划模块", description = "系统管理-行政区划模块")
public class DivisionController implements DivisionApi {

    private final DivisionService service;

    @Override
    public R<List<DivisionDTO>> all() {
        return R.ok(this.modelConvert(this.service.list()));
    }

    @PostRequest(order = 2, value = "/list/parent-id", summary = "查询行政区划(父编号)", description = "查询行政区划(父编号)")
    public R<List<DivisionDTO>> listByParentId(@RequestBody String parentId) {
        return R.ok(this.modelConvert(this.service.listByParentId(parentId)));
    }

    @PostRequest(order = 2, value = "/list/parent-no", summary = "查询行政区划(父编码)", description = "查询行政区划(父编码)")
    public R<List<DivisionDTO>> listByParentNo(@RequestBody String parentCode) {
        return R.ok(this.modelConvert(this.service.listByParentNo(parentCode)));
    }

    @PostRequest(order = 2, value = "/list/levels", summary = "查询行政区划(行政级别)", description = "查询行政区划(行政级别)")
    public R<List<DivisionDTO>> listByLevel(@RequestBody BatchParam<String> levels) {
        return R.ok(this.modelConvert(this.service.listByLevel(levels.getList())));
    }

    @PostRequest(order = 2, value = "/list/province-city", summary = "全量查询(仅省市)", description = "全量查询(仅省市)，没有查询结果时返回空列表")
    public R<List<DivisionDTO>> allProvinceAndCity() {
        return R.ok(this.modelConvert(this.service.listByLevel(Tools.Coll.newList(DivisionLevelEnum.PROVINCE.name(), DivisionLevelEnum.CITY.name()))));
    }

    private List<DivisionDTO> modelConvert(List<DivisionDO> entities) {
        return Tools.Coll.convertList(entities, entity -> {
            DivisionDTO division = Tools.Bean.copy(entity, DivisionDTO.class);
            if (null != division.getDivisionLevel()) {
                division.setLevelName(DivisionLevelEnum.valueOf(entity.getDivisionLevel()).description);
            }
            return division;
        });
    }
}
